package com.simple.api.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * test 数据库配置
 */
@Configuration
@MapperScan(basePackages = TestDataSourceConfig.PACKAGE, sqlSessionTemplateRef  = "testSqlSessionTemplate")
public class TestDataSourceConfig {

    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.simple.api.dao.test";
    static final String MAPPER_LOCATION = "classpath:mapper/test/*.xml";

   /* @Value("${test.datasource.url}")
    private String url;
    @Value("${test.datasource.username}")
    private String user;
    @Value("${test.datasource.password}")
    private String password;
    @Value("${test.datasource.driverClassName}")
    private String driverClass;*/

    @Bean(name = "testDataSource")
    @ConfigurationProperties(prefix = "srping.datasource.test")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "testSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource testDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(testDataSource);
        /*加载mybatis全局配置文件*/
        sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mapper/config/sqlMapConfig.xml"));
        /*加载所有的mapper.xml映射文件*/
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(TestDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }


    @Bean(name = "testTransactionManager")
    public DataSourceTransactionManager testTransactionManager() {
        return new DataSourceTransactionManager(testDataSource());
    }

    @Bean(name = "testSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
